#include "foldercmp.h"

#include <QtDebug>

FolderCmp::FolderCmp()
{
    clearDirList();
}

FolderCmp::~FolderCmp()
{
    clearDirList();
}

void FolderCmp::addDirectory(const QString& dir)
{
   m_dirList.append(dir);
}

void FolderCmp::excludeDirectory(const QString& dir)
{
    if (m_dirList.isEmpty()) return; //!< List already empty.

    m_dirList.removeAt(m_dirList.indexOf(dir, 0));
}

void FolderCmp::clearDirList()
{
    m_dirList.clear();
}

FolderCmpResult FolderCmp::compare()
{
    FolderCmpResult rslt;

    // Algorythm
    // 1 - Get filelist for each directory
    // 2 - compare files for not presented files
    // 3 - compare for identity files
    // 4 - ???
    // 5 - PROFIT

    QMap<int, QFileInfoList>    filesInfoList;

    QDir::Filters   dFilters = QDir::NoDotAndDotDot | QDir::Dirs | QDir::Files;
    QDir::SortFlags dSortFlags = QDir::Name;


    // Getting FileList & FileInfoList for each directory
    int dirCount = 0;
    for (QStringList::iterator it = m_dirList.begin(); it != m_dirList.end(); ++it)
    {
        QDir dir(*it, QString::null, dSortFlags, dFilters);
        filesInfoList[dirCount] = dir.entryInfoList();
        ++dirCount;
    }

    QFileInfo curFile, tgtFile;
    for (int i = 0; i < dirCount; ++i)
    {
        QMap<int, QFileInfoList>::iterator curFileInfoList = filesInfoList.find(i);
        if (curFileInfoList == filesInfoList.end()) continue;
        for (int nItemNo = 0; nItemNo < curFileInfoList->size(); nItemNo++)
        {
            FolderCmpItem rsltItemData;
            curFile = curFileInfoList->takeAt(nItemNo);
            nItemNo--;
            rsltItemData.fileinfo = curFile;
            rsltItemData.status[i] = ePresented;

            // Start to search
            for (int j = 0; j < dirCount; ++j)
            {
                if (i == j) continue;
                QMap<int, QFileInfoList>::iterator tgtFileInfoList = filesInfoList.find(j);
                if (tgtFileInfoList == filesInfoList.end()) continue;
                bool bNotFound = true;
                for (int nTargetItemNo = 0; nTargetItemNo < tgtFileInfoList->size(); nTargetItemNo++)
                {
                    tgtFile = tgtFileInfoList->at(nTargetItemNo);

                    if (curFile.fileName() == tgtFile.fileName())
                    {
                        rsltItemData.status[j] = ePresented;
                        bNotFound = false;
                        tgtFileInfoList->removeAt(nTargetItemNo);
                        nTargetItemNo--;
                        
                        // more accuracy compare needed

                        break;
                    }

                }
                if (bNotFound) rsltItemData.status[j] = eNotPresented;


            }
            rslt << rsltItemData;

        }

        

    }

    return rslt;
}
